package com.sky.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
/**
* @Description:    定义每个服务访问4次，修改继承源码的AbstractLoadBalancerRule接口
* @Author:         Joe
* @CreateDate:     2019/10/25 16:02
*/
public class RandomRule_ZDY extends AbstractLoadBalancerRule {
    //需求分析，算法策略
    //total = 0; 当total = 4时，继续向下访问
    //index = 0; 当前对外提供服务的（可以使用的服务器）地址
    //total 需要重新置为0；但是已经达到4次的.设置index = 1


    private Integer total = 0;  //总共被调用的次数
    private Integer currentIndex = 0; //当前提供服务的数组下标

    public Server choose(ILoadBalancer lb,Object key) {
        if(lb == null){
            return null;
        }
        Server server = null;
        while (server == null){
            if(Thread.interrupted()){
                return null;
            }
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if(serverCount == 0){
                return null;
            }
            /****************算法start*******************/
            if(total < 4){
                server = upList.get(currentIndex);
                total++;
            }else {
                total = 0;
                currentIndex++;
                if(currentIndex >= upList.size()){
                    currentIndex = 0;
                }
            }
            /****************算法end*******************/
            if(server == null){
                Thread.yield();
                continue;
            }
            if (server.isAlive()){
                return (server);
            }
            server = null;
            Thread.yield();
        }
        return server;
    }



    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(),key);
    }

}
